
import ResManager from "./ResManager";

export default class PoolManager {
    private constructor() { }
    private static _instance: PoolManager;
    public static get instance() {
        if (!this._instance) {
            this._instance = new PoolManager();
        }
        return this._instance;
    }
    private poolMap: Map<string, cc.NodePool> = new Map<string, cc.NodePool>();

    private getPool(name: string): cc.NodePool {
        let pool: cc.NodePool = this.poolMap[name];
        if (!pool) {
            pool = new cc.NodePool();
            this.poolMap[name] = pool;
        }
        return pool;
    }
    public put(node: cc.Node) {
        let pool = this.getPool(node.name);
        pool.put(node);
    }

    public clear(name: string) {
        let pool = this.getPool(name);
        pool.clear();
    }
    public getAsync(name: string): cc.Node {
        let pool = this.getPool(name);
        let node: cc.Node = null;
        if (pool.size() == 0) {
            let prefab = ResManager.instance.loadPrefabAsync('prefab/pool/' + name);
            cc.instantiate(prefab);
        } else {
            node = pool.get();
        }
        return node;
    }
    public async get(name: string): Promise<cc.Node> {
        let pool = this.getPool(name);
        let node: cc.Node = null;
        if (pool.size() == 0) {
            node = await ResManager.instance.loadPrefab('prefab/pool/' + name);
        } else {
            node = pool.get();
        }
        return node;
    }
}
